<template>
  <div class="app-header">
    <el-tag v-if="connected" type="success">服务已连接</el-tag>
    <el-tag v-else type="danger">服务未连接</el-tag>

    <el-tag v-if="isGameStarted" type="success">游戏进行中</el-tag>
    <el-tag v-else type="info">游戏未开始</el-tag>

    <el-tag v-if="countDown" type="danger">已有玩家猜中答案，开启游戏结束倒计时: {{ num }}</el-tag>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import socket from '../../../socket/index'
export default {
  data: function() {
    return {
      // 倒计时时间
      num: 30,
      // 倒计时定时器函数标识
      time: null
    }
  },
  computed: {
    // 读取vuex中的state.connected
    ...mapState(['connected', 'countDown']),
    // 读取vuex中的gettes属性
    ...mapGetters(['isGameStarted'])
  },
  watch: {
    // 开启游戏倒计时
    countDown(nval) {
      if (nval) {
        this.time = setInterval(() => {
          this.num--
          if (this.num === 0) {
            clearInterval(this.time)
            socket.emit('stop_game', true)
            this.$store.commit('updateHolder', '')
            this.$store.commit('updateLines', '')
            this.$store.commit('updateCountDown', false)
          }
        }, 1000)
      } else {
        // 倒计时文字隐藏了，同时清除定时器和重30开头
        this.time && clearInterval(this.time)
        this.num = 30
      }
    }

  }
}
</script>

<style scoped>
.el-tag {
  margin-right: 10px;
}
</style>
